package com.gserver.test;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gserver.commons.ByteArray;
import com.gserver.netty.domain.Message;

/**
 * 
 */
public class ClientHandler extends SimpleChannelUpstreamHandler {
	private static final Logger logger = LoggerFactory
			.getLogger(ClientHandler.class);

	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
		Channel c = e.getChannel();
		ByteArray s = new ByteArray();
		// 协议类型
		s.writeArray(1);

		Message msg = new Message((short) 1000, (short) 1, s.toArray(), ctx);
		c.write(msg);

	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {

		Message msg = (Message) e.getMessage();

		System.out
				.println("client received message:" + msg.getHandler() + "\t");

	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
		// Close the connection when an exception is raised.
		logger.warn("Unexpected exception from downstream.", e.getCause());
		e.getChannel().close();
	}

}
